﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Snowdreamist.Threading;
using SNSpirit.Service.Certificate;

namespace SNSpirit.Service.Authentication.Integrated
{
    public class NamePasswordAuthentication : AuthenticationServiceBase
    {
        public NamePasswordAuthentication(INamePasswordAuthenticationConnector connector)
        {
            if (connector == null)
                throw new ArgumentNullException("validator");
            this._connector = connector;
            this._connector.AuthenticationStateChanged += new EventHandler(Connector_AuthenticationStateChanged);
        }

        public override AuthResult Authenticate(ICertificate certificate)
        {
            if (!(certificate is INamePasswordCertificate))
                throw new ArgumentException("Invalid certificate type");

            var token = this._connector.Validate((INamePasswordCertificate)certificate, null);
            AuthResult result = new AuthResult(token, null);

            return result;
        }

        public override LogoutResult Logout()
        {
            return this._connector.Logout(this.Token);
        }

        protected override AuthResult GetAuthenticationState()
        {
            return this._connector.GetAuthenticationState();
        }

        #region private

        private void Connector_AuthenticationStateChanged(object sender, EventArgs e)
        {
            BackgroundJob.Run(new Action(() =>
                {
                    var r = this._connector.GetAuthenticationState();
                    this.OnStateChanged(r.Token, r.Error);
                }));
        }

        private INamePasswordAuthenticationConnector _connector;

        #endregion private
    }
}